var express = require('express')
var path = require('path')
var request = require('request')
const bodyParser = require('body-parser')

var app = express()

app.use(express.static(path.resolve(__dirname, '../dist/')))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/', function (req, res) {
  res.sendFile(path.resolve(__dirname, '../dist/') + '/index.html')
})

app.get('/api/**', function (req, res) {
  var url = req.originalUrl
  url = 'http://localhost:8083/' + url

  var body = req.body
  var token = req.cookies && req.cookies['Authorition']
  for (var p in body) {
    if (!body[p] || body[p] == '') {
      delete body[p]
    }
  }
  var head = {
    'authorization': token
  }
  var opts = {
    headers: head,
    url: 'http://www.163.com',
    json: true,
    form: body
  }

  request.get(opts, function (err, resp, data) {
    res.send(data)
  })
})

app.post('/api/**', function (req, res) {
  var url = req.originalUrl
  url = 'http://localhost:8083/' + url

  var body = req.body
  var token = req.cookies && req.cookies['Authorition']
  for (var p in body) {
    if (!body[p] || body[p] == '') {
      delete body[p]
    }
  }
  var head = {
    'authorization': token
  }
  var opts = {
    headers: head,
    url: url,
    json: true,
    form: body
  }

  request.post(opts, function (err, resp, data) {
    res.send(data)
  })
})

var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  console.log('应用实例，访问地址为 http://%s:%s', host, port)
})
